Hello,
I want to get the top 3 highest-paid employees in each department from the
Employee table. How can I write this query in SQL Server?
home / developersection / forums / how to write a query to get top n records per group in sql server?
Hello,
I want to get the top 3 highest-paid employees in each department from the
Employee table. How can I write this query in SQL Server?
Ravi Vishwakarma
16-Jul-2024To get the top 3 highest-paid employees in each department from the
Employeetable in SQL Server, you can use theROW_NUMBER()window function along with a Common Table Expression (CTE) or a subquery.Here is an example query:
Using CTE
Explanation:
WITH RankedEmployees AS (...)part defines a Common Table Expression (CTE) namedRankedEmployees.ROW_NUMBER() OVER (PARTITION BY DepartmentID ORDER BY Salary DESC)assigns a unique rank to each employee within their department, ordered by salary in descending order.SELECTstatement outside the CTE filters the results to include only those rows whereRowNumis less than or equal to 3, effectively selecting the top 3 highest-paid employees in each department.Using Subquery
Alternatively, you can achieve the same result using a subquery:
Read more
Help with Writing a Subquery to Get Aggregate Data in SQL Server
What is the order of execution process of subquery in SQL?
Can we use ORDER BY in subquery in SQL?
Explain the difference between a subquery and a join in SQL Server.